package edu.colorado.epmapp.network;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import edu.colorado.epmapp.models.User;

public class BaseNetwork {
	
	//PROD: "http://epm.cs.colorado.edu/"
	//STAGING: "http://epic-research.cs.colorado.edu:8888/"
	
	String baseURL = "http://epic-research.cs.colorado.edu:8888/api/v1/";
	
	int TIMEOUT_MS = 10000; //10 seconds
	
	DefaultHttpClient client;
	
	
	/**
	 * 
	 * BaseNetwork constructor, the baseURL is specified above and it is
	 * generally better to use this instead of specifying a new base.
	 * 
	 * @param newBase - The new baseURL to use
	 */
	public BaseNetwork(String newBase){
		super();
		if(newBase != null){
			baseURL = newBase;
		}
		
		HttpParams httpParams = new BasicHttpParams();
		// Set the timeout in milliseconds until a connection is established.
		// The default value is zero, that means the timeout is not used. 
		int timeoutConnection = 3000;
		HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
		// Set the default socket timeout (SO_TIMEOUT) 
		// in milliseconds which is the timeout for waiting for data.
		int timeoutSocket = 5000;
		HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
		client = new DefaultHttpClient(httpParams);
	}
	
	/**
	 * 
	 * This method sends a HttpPost request and receives the server response.
	 * 
	 * @param url - The rest of the URL to add to the baseURL, 
	 *              specific to the endpoint you wish to hit
	 * @param data - The JSON encoded data to send in the request body
	 * @param listener - the callback listener
	 */
	protected void submitRequest(String url, String data, OnResponseListener listener){ 
		client.getCredentialsProvider().setCredentials(
				new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
				new UsernamePasswordCredentials(User.getUser().getUsername(), User.getUser().getPassword()));
		HttpPost postRequest = new HttpPost(baseURL+url);
		postRequest.setHeader("Content-Type", "application/json");
		
		HttpResponse response;
		String finalResponse = null;
		try {
			StringEntity stringEntity = new StringEntity(data);
			postRequest.setEntity(stringEntity);
			response = client.execute(postRequest);
			finalResponse = response.getStatusLine().toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("error: "+e.toString());
		}
		
		listener.onRequestComplete(finalResponse);
	}
	
}
